package com.zhubayi.controller;

import com.zhubayi.constant.MyConstant;
import com.zhubayi.entity.Favor;
import com.zhubayi.entity.R;
import com.zhubayi.entity.User;
import com.zhubayi.service.FavorService;
import com.zhubayi.service.VideoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author 祝八一
 */
@Controller
@RequestMapping("favor")
public class FavorController {
    @Autowired
    FavorService favorService;
    @Autowired
    VideoService videoService;
    @ResponseBody
    @GetMapping("/add/{id}")
    @Transactional
    public R add(HttpServletRequest request, @PathVariable("id") Integer id){
        HttpSession session = request.getSession();
        User user =(User) session.getAttribute("user");
        if (user==null){
            //没有登录
            return new  R(MyConstant.AUTHENTICATION);
        }
        if (favorService.isRepeat(id,user.getId())){
            return new  R(MyConstant.FAVORREPEAT);
        }
        Favor favor = new Favor();
        favor.setFavorTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        favor.setUserId(user.getId());
        favor.setVideoId(id);
        //添加视频
        favorService.add(favor);
        //增加收藏次数
        videoService.addPraiseNum(id);
        return new R(MyConstant.OK);
    }
    @ResponseBody
    @RequestMapping("/del/{id}")
    public R del(HttpServletRequest request,@PathVariable("id") Integer id){
        HttpSession session = request.getSession();
        User user =(User) session.getAttribute("user");
        if (user==null){
            //没有登录
            return new  R(MyConstant.AUTHENTICATION);
        }
        favorService.deleteByUId(user.getId(),id);
        return new R(MyConstant.OK);
    }
}
